package com.mnxiaotu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mnxiaotu.common.vo.Result;
import com.mnxiaotu.entity.PageBean;
import com.mnxiaotu.entity.Role;
import com.mnxiaotu.entity.RoleMenu;
import com.mnxiaotu.entity.UserRole;
import com.mnxiaotu.service.RoleMenuService;
import com.mnxiaotu.service.RoleService;
import com.mnxiaotu.service.UserRoleService;
import com.mnxiaotu.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 86182
 */
@RestController
@RequestMapping("/sys/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleMenuService roleMenuService;

    /**
     * 获取所有角色列表
     *
     * @param
     * @return
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result listAll() {
        Map<String, Object> resultMap = new HashMap<>();
        List<Role> roleList = roleService.list();
        resultMap.put("roleList", roleList);
        return Result.ok(resultMap);
    }

    /**
     * 根据条件分页查询角色信息
     *
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result list(@RequestBody PageBean pageBean) {
        //获取查询条件
        String query = pageBean.getQuery().trim();
        //根据查询条件查询后分页
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>().like(StringUtil.isNotEmpty(query), "rolename", query);
        Page<Role> pageResult = roleService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), roleQueryWrapper);
        //返回分页后的数据集合
        List<Role> roleList = pageResult.getRecords();
        //前端返回分页结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", pageResult.getTotal());
        return Result.ok(resultMap);
    }

    /**
     * 添加或者修改角色
     *
     * @param role
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')" + "||" + "hasAuthority('system:role:edit')")
    public Result save(@RequestBody Role role) {
        if (role.getId() == null || role.getId() == -1) {
            role.setCreateTime(new Date());
            roleService.save(role);
        } else {
            role.setUpdateTime(new Date());
            roleService.updateById(role);
        }
        return Result.ok();
    }

    /**
     * 根据id查询角色
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result findById(@PathVariable(value = "id") Integer id) {
        Role role = roleService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("role", role);
        return Result.ok(map);
    }

    /**
     * 验证角色名
     *
     * @param role
     * @return
     */
    @PostMapping("/checkRoleName")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result checkRoleName(@RequestBody Role role) {
        //判断角色是否重复
        if (roleService.getByRolename(role.getRolename()) == null) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    /**
     * 删除角色
     *
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:role:delete')")
    public Result delete(@RequestBody Long[] ids) {
        roleService.deleteByIds(Arrays.asList(ids));
        // 删除用户角色关联表中与这些用户相关的记录
        userRoleService.remove(new QueryWrapper<UserRole>().in("role_id", ids));
        return Result.ok();
    }

    /**
     * 获取当前角色的权限菜单ID集合
     *
     * @param id
     * @return
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public Result menus(@PathVariable(value = "id") Integer id) {
        List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
        return Result.ok().put("menuIdList", menuIdList);
    }


    /**
     * 更新角色权限信息
     *
     * @param id
     * @return
     */
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public Result updateMenus(@PathVariable(value = "id") Long id, @RequestBody long[] menuIds) {
        //清空该id的menu记录
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("role_id", id));
        List<RoleMenu> roleMenuList = new ArrayList<>();
        //存入新的menu记录
        Arrays.stream(menuIds).forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);
            roleMenuList.add(roleMenu);
        });
        roleMenuService.saveBatch(roleMenuList);
        return Result.ok();
    }
}
